package com.data.modules.smzh.controller;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.domain.Person;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.data.common.api.vo.DeviceResult;
import com.data.common.api.vo.Result;
import com.data.common.aspect.annotation.AutoLog;
import com.data.common.constant.WebsocketConst;
import com.data.common.constant.enums.DySmsEnum;
import com.data.common.constant.enums.EventEnum;
import com.data.common.util.*;
import com.data.modules.base.service.BaseCommonService;
import com.data.modules.message.websocket.WebSocket;
import com.data.modules.mqt.MqttPushClient;
import com.data.modules.sm.entity.SmRepairStats;
import com.data.modules.sm.entity.SysConfig;
import com.data.modules.sm.service.ISmRepairStatsService;
import com.data.modules.sm.service.ISysConfigService;
import com.data.modules.smzh.entity.*;
import com.data.modules.smzh.service.*;
import com.data.modules.smzh.vo.*;
import com.data.modules.system.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Instant;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @Author boot
 */

@RestController
@RequestMapping("/device/api")
@Api(tags="门禁机设备")
@Slf4j
@SuppressWarnings("ALL")
public class ThirdController<stringWarnType> {

	@Autowired
	private IFacedeviceService facedeviceService;

	@Autowired
	private MqttPushClient mqttPushClient;

	@Autowired
	private ISmDeviceLogsService smDeviceLogsService;


	@AutoLog(value = "摔倒设备心跳接口")
	@ApiOperation("摔倒设备心跳接口")
	@PostMapping(value = "/ed719/heartBeat")
	public Map heartBeat(@RequestBody FallReqVo reqVo)  {
		log.info("摔倒设备心跳接口请求参数{}",JSONObject.toJSONString(reqVo));
		String data = reqVo.getData();
		String mac = reqVo.getMac();

		//进行加减密获取mac 地址可以保存添加设备使用 最后在线时间
		Map<String,Object> map = new HashMap<>();
		map.put("code",200);
		map.put("ts", Instant.now().getEpochSecond());
		map.put("message","成功");
		return map;
	}

	@AutoLog(value = "摔倒设备报警上报")
	@ApiOperation("摔倒设备报警上报")
	@PostMapping(value = "/ed719/alarm")
	public Map alarm(@RequestBody FallReqVo reqVo)  {
		log.info("摔倒设备报警上报请求参数{}",JSONObject.toJSONString(reqVo));
		String data = reqVo.getData();

		try {
			//获取key
			String secretKey = DataSecurityUtil.generateMcuSecretKey(reqVo.getMac(),reqVo.getTs());
			String decrypt = DataSecurityUtil.decrypt(data, secretKey);

			log.info("解密数据{}",decrypt);
			JSONObject json = JSON.parseObject(decrypt);
			String value = json.getString("alarmValue");

			String eventName = "";

			if(ObjectUtil.equals(value,"3101")){
				eventName = "摔倒报警";
			}else if (ObjectUtil.equals(value,"3102")){
				eventName = "疑似摔倒";
			}

			if(ObjectUtil.isNotEmpty(eventName)){
				SmDeviceLogs smDeviceLogs = new SmDeviceLogs();
				smDeviceLogs.setDeviceId(reqVo.getMac());
				smDeviceLogs.setEventName(eventName);
				smDeviceLogs.setDeviceType(4);

				smDeviceLogsService.sendMessage(smDeviceLogs,"smVip009", EventEnum.TYPE_ALARM.getCode());
			}

		} catch (Exception e) {
			log.error("加密失败",e.getMessage(), e);
		}

		Map<String,Object> map = new HashMap<>();
		map.put("code",200);
		map.put("ts", Instant.now().getEpochSecond());
		map.put("message","成功");

		return map;
	}

	@AutoLog(value = "获取状态推送开关")
	@ApiOperation("获取状态推送开关")
	@PostMapping(value = "/ed719/getPushSwitch")
	public Map getPushSwitch(@RequestBody FallReqVo reqVo)  {
		log.info("获取状态推送开关请求参数{}",JSONObject.toJSONString(reqVo));
		Long ts = System.currentTimeMillis();
		Map<String,Object> resultMap = new HashMap<>();
		//1 代表推送 0 代表不推送
		resultMap.put("peopleStateSwitch",1);//有无人推送开关
		resultMap.put("activeStateSwitch",0); //活动推送开关

		//获取key
		String value = "";
		try {
			String secretKey = DataSecurityUtil.generateMcuSecretKey(reqVo.getMac(),reqVo.getTs());
			value = DataSecurityUtil.encrypt(JSONObject.toJSONString(resultMap),secretKey);
		} catch (Exception e) {
			log.error("加密失败",e.getMessage(), e);
		}

		//设置推送开关
		Map<String,Object> map = new HashMap<>();
		map.put("code",200);
		map.put("ts", Instant.now().getEpochSecond());
		map.put("data",value);

		return map;
	}

	@AutoLog(value = "摔倒设备状态接收")
	@ApiOperation("摔倒设备状态接收")
	@PostMapping(value = "/ed719/pushStatus")
	public Map pushStatus(@RequestBody FallReqVo reqVo)  {
		log.info("摔倒设备状态接收请求参数{}",JSONObject.toJSONString(reqVo));
		Long ts = System.currentTimeMillis();

		//获取key
		String value = "";
		try {
			String secretKey = DataSecurityUtil.generateMcuSecretKey(reqVo.getMac(),reqVo.getTs());
			value = DataSecurityUtil.decrypt(JSONObject.toJSONString(reqVo.getData()),secretKey);
			JSONObject jsonObject = JSONObject.parseObject(value);
			String peopleState = jsonObject.getString("peopleState");
			String activeState = jsonObject.getString("activeState");

			log.info("解密数据{}",value);

		} catch (Exception e) {
			log.error("解密失败",e.getMessage(), e);
		}

		//设置推送开关
		Map<String,Object> map = new HashMap<>();
		map.put("code",200);
		map.put("ts", Instant.now().getEpochSecond());

		return map;
	}



	@ApiOperation("云门禁通信接口")
	@PostMapping(value = "/v1/qr_gate")
	public Map qr_gate(@RequestBody ThirdDoorReqVo deviceReqVo)  {
		log.info("云门禁通信接口请求参数{}",JSONObject.toJSONString(deviceReqVo));
		String apiId = deviceReqVo.getApiId();
		String bizContent = deviceReqVo.getBizContent();

		//base64 解密
		byte[] decodedBytes = Base64.getDecoder().decode(bizContent);
		String decodedString = new String(decodedBytes);
		log.info("gere{}",decodedString);
		JSONObject jsonObj = JSON.parseObject(decodedString);

		if(ObjectUtil.equals("dev_register",apiId)){//注册设备

			DevRegister devRegister =JSON.parseObject(decodedString,DevRegister.class);

			Map<String,Object> map = new HashMap<>();
			map.put("TimeStamp",devRegister.getTimeStamp());
			map.put("time",String.valueOf(System.currentTimeMillis()));
			map.put("msg","success");
			map.put("ListVer",1);

			return map;

		}else if(ObjectUtil.equals("dev_list",apiId)){//查询设备列表

			DevRegister devRegister =JSON.parseObject(decodedString,DevRegister.class);
			//通过小区编号 查询设备列表

			List list = new ArrayList();

			list.add(devRegister);

			Map<String,Object> map = new HashMap<>();
			map.put("TimeStamp",devRegister.getTimeStamp());
			map.put("time",String.valueOf(System.currentTimeMillis()));
			map.put("msg","success");
			map.put("list",list);

			return map;
		}else if(ObjectUtil.equals("user_apply",apiId)){//用户申请

			UserApply userApply = JSON.parseObject(decodedString,UserApply.class);

			Map<String,Object> map = new HashMap<>();
			map.put("TimeStamp",userApply.getTimeStamp());
			map.put("time",String.valueOf(System.currentTimeMillis()));
			map.put("msg","success");

			return map;

		}else if(ObjectUtil.equals("user_list",apiId)){//用户列表获取

			UserApply userApply = JSON.parseObject(decodedString,UserApply.class);

			Map<String,Object> map = new HashMap<>();
			map.put("TimeStamp",userApply.getTimeStamp());
			map.put("time",String.valueOf(System.currentTimeMillis()));
			map.put("msg","fail");

			return map;

		}else if(ObjectUtil.equals("user_register",apiId)){// 用户注册

			UserApply userApply = JSON.parseObject(decodedString,UserApply.class);

			Map<String,Object> map = new HashMap<>();
			map.put("TimeStamp",userApply.getTimeStamp());
			map.put("time",String.valueOf(System.currentTimeMillis()));
			map.put("msg","success");

			return map;

		}else if(ObjectUtil.equals("user_delete",apiId)){// 删除用户

			UserApply userApply = JSON.parseObject(decodedString,UserApply.class);

			Map<String,Object> map = new HashMap<>();
			map.put("TimeStamp",userApply.getTimeStamp());
			map.put("time",String.valueOf(System.currentTimeMillis()));
			map.put("msg","success");
			return map;

		}else if(ObjectUtil.equals("user_limit",apiId)){//  用户权限获取

			UserApply userApply = JSON.parseObject(decodedString,UserApply.class);

			Map<String,Object> map = new HashMap<>();
			map.put("TimeStamp",userApply.getTimeStamp());
			//map.put("time",String.valueOf(System.currentTimeMillis()));
			map.put("msg","fail");
			return map;
		}else if(ObjectUtil.equals("visitor_limit",apiId)){//生成访客码

			UserApply userApply = JSON.parseObject(decodedString,UserApply.class);

			Map<String,Object> map = new HashMap<>();
			map.put("TimeStamp",userApply.getTimeStamp());
			//map.put("time",String.valueOf(System.currentTimeMillis()));
			map.put("msg","fail");
			return map;

		}else if(ObjectUtil.equals("upload_record",apiId)){//上报开门记录

			UserApply userApply = JSON.parseObject(decodedString,UserApply.class);

			Map<String,Object> map = new HashMap<>();
			map.put("TimeStamp",userApply.getTimeStamp());
			map.put("time",String.valueOf(System.currentTimeMillis()));
			map.put("msg","fail");
			return map;
		}else if(ObjectUtil.equals("download_record",apiId)){//查询开门记录

			UserApply userApply = JSON.parseObject(decodedString,UserApply.class);

			Map<String,Object> map = new HashMap<>();
			map.put("TimeStamp",userApply.getTimeStamp());
			map.put("time",String.valueOf(System.currentTimeMillis()));
			map.put("msg","fail");
			return map;

		}else if(ObjectUtil.equals("upload_heart",apiId)){//上报心跳

			DevRegister userApply = JSON.parseObject(decodedString,DevRegister.class);

			//通过 心跳 更新状态
		/*	log.info("心跳客户端sn: " + userApply.getDevSn());
			facedeviceService.synMsgBySn(userApply.getDevSn());*/

			Map<String,Object> map = new HashMap<>();
			map.put("TimeStamp",userApply.getTimeStamp());
			map.put("time",String.valueOf(System.currentTimeMillis()));
			map.put("msg","success");
			return map;
		}

		return null;

	}

	@PostMapping("/v1/publishMsg")
	@ApiOperation(value="mqtt发送消息", notes="mqtt发送消息")
	public void publishMsg(@RequestBody ThirdDoorReqVo deviceReqVo){

		String topic = deviceReqVo.getApiId();
		String message =  deviceReqVo.getSign();
		log.info("主体:{},消息：{}" ,topic,message);

		mqttPushClient.publish(topic,message);
	}


}
